package com.gxa.ssm340.controller;

import com.gxa.ssm340.common.R;
import com.gxa.ssm340.entity.dto.CpnDTO;
import com.gxa.ssm340.entity.dto.UpDownDTO;
import com.gxa.ssm340.entity.pojo.Coupon1;
import com.gxa.ssm340.entity.vo.CpnVO;
import com.gxa.ssm340.exception.BizException;
import com.gxa.ssm340.service.CouponService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * 优惠券管理控制器
 */
@Api(value = "优惠券控制器",tags = "查询优惠价有关操作接口")
@RestController
@RequestMapping("/cpn")
public class CouponController {
    @Autowired
    private CouponService couponService;

    @ApiOperation(value = "查询所有优惠券方法")
    @GetMapping("/getList")
    public R selectCouponAll(@Param("cpnDTO") CpnDTO cpnDTO){
        CpnVO cpnVO = new CpnVO();

        List<Coupon1> coupons = couponService.selectCouponAll(cpnDTO);
        Integer integer = couponService.selectCouponAllCount();
        cpnVO.setCoupon(coupons);
        cpnVO.setCount(integer);

        return R.success(cpnVO);
    }


    @ApiOperation(value = "添加一条优惠券方法",notes = "\"collectExp\": \"2023-10-19 12:13:33\",\n" +
            "  \"desc\": \"满200减20\",\n" +
            "  \"img\": \"/img/b.jpg\",\n" +
            "  \"name\": \"新年优惠券\",\n" +
            "  \"role\": \"会员用\",\n" +
            "  \"usedExp\": \"2023-10-29 12:13:33\"")
    @PostMapping("/add")
    public R insertCoupon(@RequestBody Coupon1 coupon) throws BizException {
        Integer integer = couponService.insertCoupon(coupon);
        return R.success(coupon);
    }

    @ApiOperation(value = "控制优惠券上下架的方法",notes = "")
    @PostMapping("/update")
    public R updateUpAndDown(@RequestBody UpDownDTO upDownDTO) throws BizException {
        couponService.updateUpAndDown(upDownDTO);
        return R.success(true);
    }

    @ApiOperation(value = "删除优惠券的方法",notes = "")
    @PostMapping("/delete")
    public R updateCpn( Integer id) throws BizException {
        couponService.delete(id);
        return R.success(true);
    }
    @PostMapping("/upload")
    public R uploadImg(@RequestParam("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();

        //获取文件名，并处理
        //获取后缀
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));

        //为了保证文件名在服务器中唯一
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");

        //创建本地文件（File）
        String root = "d:/img/";
        String destFileName = root+fileName+ext;
        //把上传的数据写入到本地文件
        File file1 = new File(destFileName);
        file.transferTo(file1);
        //为了让前端可以访问到资源，把路径返回
        return R.success("/img/"+fileName+ext);
    }


}
